package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.byit.builder.MapBuilder;
import com.byit.domain.AppEnterpriseAuthentication;
import com.byit.domain.AppUser;
import com.byit.domain.AppUserAuthentication;
import com.byit.enums.PromptInfo;
import com.byit.jwt.ann.JwtUser;
import com.byit.jwt.domain.JwtSession;
import com.byit.msg.MessageResult;
import com.byit.service.IAppEnterpriseAuthenticationService;
import com.byit.service.IAppUserAuthenticationService;
import com.byit.service.IAppUserService;
import com.byit.utils.IdcardUtil;
import com.byit.utils.MinioUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;


/**
 * 企业认证
 *
 * @author tjm
 * @date 2019年1月9日
 */
@RestController
@RequestMapping("/app/enterpriseAuth")
public class AppEnterpriseAuthenticationController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppUserAuthenticationService appUserAuthenticationService;
    @Autowired
    private IAppEnterpriseAuthenticationService enterpriseAuthenticationService;
    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private MinioUtil minioUtil;


    /**
     * app用户查询企业认证详情
     */
    @GetMapping("/list")
    public Object list(@JwtUser JwtSession session) {
        if (!session.isLogin()) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        Long userId = session.userId();
        List<AppEnterpriseAuthentication> enterpriseAuthenticationList = enterpriseAuthenticationService.selectByMap(
                MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
        if (enterpriseAuthenticationList.size() == 0) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NULL);
        }

        return MessageResult.success(enterpriseAuthenticationList);
    }

    /**
     * app用户查询企业认证详情
     */
    @GetMapping("/details")
    public Object details(@JwtUser JwtSession session) {
        if (!session.isLogin()) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        Long userId = session.userId();
        List<AppEnterpriseAuthentication> enterpriseAuthenticationList = enterpriseAuthenticationService.selectByMap(
                MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
        if (enterpriseAuthenticationList.size() == 0) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NULL);
        } else if (enterpriseAuthenticationList.size() > 1) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
        }

        return MessageResult.success(enterpriseAuthenticationList.get(0));
    }

    /**
     * 添加企业认证
     */
    @PostMapping("/add")
    public Object add(@JwtUser JwtSession session, @RequestParam("legalName") String legalName,
                      @RequestParam("idCardNo") String idCardNo,
                      @RequestParam("creditNo") String creditNo,
                      @RequestParam("companyName") String companyName,
                      @RequestParam("phone") String phone,
                      @RequestParam("idCardFace") MultipartFile idCardFace,
                      @RequestParam("idCardCon") MultipartFile idCardCon,
                      @RequestParam("licensePic") MultipartFile licensePic) {
        try {
            if (!session.isLogin()) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            Long userId = session.userId();
            //检查身份证是否合法
            if (!IdcardUtil.validateCard(idCardNo)) {
                return MessageResult.warpper(PromptInfo.ERROR_ID_CARD);
            }
            //检查该用户是否已认证
            List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("user_id", userId).setParam("is_del", 0).setParam("status", 2).ok());
            if (appUserAuthentications.size() == 0) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_NOT_AUTH);
            }
            //检查该用户是否已经有该企业认证
            List<AppEnterpriseAuthentication> userHaves = enterpriseAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("credit_no", creditNo).setParam("user_id", userId).setParam("is_del", 0).ok());
            if (userHaves.size() > 0) {
                return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_USER_HAVE);
            }
            //检查该用户是否已经有该企业认证
            List<AppEnterpriseAuthentication> companyHaves = enterpriseAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("company_name", companyName).setParam("user_id", userId).setParam("is_del", 0).ok());
            if (companyHaves.size() > 0) {
                return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_USER_HAVE);
            }
            //根据信用机构代码查询该企业是否已被认证
            List<AppEnterpriseAuthentication> haves = enterpriseAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("credit_no", creditNo).setParam("status", 2).setParam("is_del", 0).ok());
            if (haves.size() > 0) {
                return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_HAVE);
            }
            AppEnterpriseAuthentication enterpriseAuthentication = new AppEnterpriseAuthentication();
            //上传身份证正面图片
            JSONObject flg = minioUtil.uploadFile(idCardFace.getInputStream(),
                    idCardFace.getOriginalFilename().substring(idCardFace.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/idCardFace/");
            if ("1".equals(flg.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                enterpriseAuthentication.setIdCardFace(flg.getString("path"));
            }
            //上传身份证反面图片
            JSONObject flg2 = minioUtil.uploadFile(idCardCon.getInputStream(),
                    idCardCon.getOriginalFilename().substring(idCardCon.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/idCardCon/");
            if ("1".equals(flg2.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                enterpriseAuthentication.setIdCardCon(flg2.getString("path"));
            }
            //上传营业执照
            JSONObject flg3 = minioUtil.uploadFile(licensePic.getInputStream(),
                    licensePic.getOriginalFilename().substring(licensePic.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/licensePic/");
            if ("1".equals(flg3.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                enterpriseAuthentication.setLicensePic(flg3.getString("path"));
            }
            enterpriseAuthentication.setUserId(userId);
            enterpriseAuthentication.setOperationId(userId);
            enterpriseAuthentication.setLegalName(legalName);
            enterpriseAuthentication.setIdCardNo(idCardNo);
            enterpriseAuthentication.setCompanyName(companyName);
            enterpriseAuthentication.setPhone(phone);
            enterpriseAuthentication.setCreditNo(creditNo);
            enterpriseAuthentication.setCreateTime(new Date());
            enterpriseAuthentication.setUpdateTime(enterpriseAuthentication.getCreateTime());
            if (enterpriseAuthenticationService.insert(enterpriseAuthentication)) {
                //修改app_user表认证状态
                AppUser appUser = new AppUser();
                appUser.setId(userId);
                appUser.setAuthState(4);
                appUserService.updateById(appUser);
                return MessageResult.warpper("000", null, "企业认证信息提交成功");
            }
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_FILED);
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_FILED);
        }
    }

    /**
     * 修改企业认证
     */
    @PostMapping("/update")
    public Object update(@JwtUser JwtSession session, @RequestParam("id") Long id, String legalName, String idCardNo, String companyName,
                         String creditNo, String phone, MultipartFile idCardFace, MultipartFile idCardCon, MultipartFile licensePic) {
        try {
            if (!session.isLogin()) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            AppEnterpriseAuthentication authentication = new AppEnterpriseAuthentication();
            Long userId = session.userId();
            if (StringUtil.isNotEmpty(idCardNo)) {
                //检查身份证是否合法
                if (!IdcardUtil.validateCard(idCardNo)) {
                    return MessageResult.warpper(PromptInfo.ERROR_ID_CARD);
                }
                authentication.setIdCardNo(idCardNo);
            }
            //检查该用户企业是否存在认证信息
            List<AppEnterpriseAuthentication> haves = enterpriseAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("user_id", userId).setParam("is_del", 0).setParam("credit_no", creditNo).ok());
            if (haves.size() > 1) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
            } else if (haves.size() == 0) {
                return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_NULL);
            }

            AppEnterpriseAuthentication oldAuth = haves.get(0);
            if (!oldAuth.getId().equals(id)) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
            }
            if (oldAuth.getStatus() != 3) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NOT_UPDATE);
            }
            //检查该企业信用代码是否已被使用
            if (StringUtil.isNotEmpty(creditNo)) {
                List<AppEnterpriseAuthentication> haveIdCards = enterpriseAuthenticationService.selectByMap(
                        MapBuilder.newMap(3).setParam("credit_no", creditNo).setParam("status", 2).setParam("is_del", 0).ok());
                if (haveIdCards.size() > 0) {
                    return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_HAVE);
                }
                authentication.setCreditNo(creditNo);
            }

            //检查该企业信用代码是否已被使用
            if (StringUtil.isNotEmpty(companyName)) {
                List<AppEnterpriseAuthentication> haveCards = enterpriseAuthenticationService.selectByMap(
                        MapBuilder.newMap(3).setParam("company_name", companyName).setParam("status", 2).setParam("is_del", 0).ok());
                if (haveCards.size() > 0) {
                    return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_HAVE);
                }
                authentication.setCompanyName(companyName);
            }

            //上传身份证正面图片
            if (null != idCardFace) {
                JSONObject flg = minioUtil.uploadFile(idCardFace.getInputStream(),
                        idCardFace.getOriginalFilename().substring(idCardFace.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/idCardFace/");
                if ("1".equals(flg.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setIdCardFace(flg.getString("path"));
                }
            }
            //上传身份证反面图片
            if (null != idCardCon) {
                JSONObject flg2 = minioUtil.uploadFile(idCardCon.getInputStream(),
                        idCardCon.getOriginalFilename().substring(idCardCon.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/idCardCon/");
                if ("1".equals(flg2.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setIdCardCon(flg2.getString("path"));
                }
            }
            //上传营业执照图片
            if (null != licensePic) {
                JSONObject flg3 = minioUtil.uploadFile(licensePic.getInputStream(),
                        licensePic.getOriginalFilename().substring(licensePic.getOriginalFilename().lastIndexOf(".")), "authentication/enterprise/licensePic/");
                if ("1".equals(flg3.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setLicensePic(flg3.getString("path"));
                }
            }
            authentication.setId(oldAuth.getId());
            if (StringUtil.isNotEmpty(legalName)) {
                authentication.setLegalName(legalName);
            }
            if (StringUtil.isNotEmpty(phone)) {
                authentication.setPhone(phone);
            }

            authentication.setUpdateTime(new Date());
            authentication.setStatus(1);
            if (enterpriseAuthenticationService.updateById(authentication)) {
                //修改app_user表认证状态
                AppUser appUser = new AppUser();
                appUser.setId(userId);
                appUser.setAuthState(4);
                appUserService.updateById(appUser);
                return MessageResult.warpper("000", null, "企业认证信息修改成功");
            }
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_FILED);
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_FILED);
        }
    }

    /**
     * 删除企业认证信息
     */
    @PostMapping("/delete")
    public Object delete(@JwtUser JwtSession session, @RequestParam("id") Long id) {
        if (!session.isLogin()) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        Long userId = session.userId();
        //检查该企业认证是否可以删除
        List<AppEnterpriseAuthentication> authentications = enterpriseAuthenticationService.selectByMap(
                MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).setParam("id", id).ok());
        if (authentications.size() == 0) {
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_NULL);
        }

        AppEnterpriseAuthentication oldAuth = authentications.get(0);
        if (oldAuth.getStatus() != 3) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NOT_DEL);
        }
        AppEnterpriseAuthentication authentication = new AppEnterpriseAuthentication();
        authentication.setId(oldAuth.getId());
        authentication.setIsDel(1);
        authentication.setUpdateTime(new Date());
        if (enterpriseAuthenticationService.updateById(authentication)) {
            //修改app_user表认证状态
            AppUser appUser = new AppUser();
            appUser.setId(userId);
            appUser.setAuthState(2);
            appUserService.updateById(appUser);
            return MessageResult.warpper("000", null, "企业认证信息删除成功");
        } else {
            return MessageResult.warpper(PromptInfo.ERROR_ENT_AUTH_DEL_FILED);
        }
    }

}
